package com.identify.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.identify.pojos.entity.Detection;
import com.identify.pojos.vos.ApiDetectionVo;
import com.identify.pojos.vos.BoxVo;
import com.identify.service.InferenceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.identify.properties.ModelProperties;
import org.springframework.beans.factory.annotation.Autowired;
import com.identify.utils.HttpClientUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class InferenceServiceImpl implements InferenceService {

    @Autowired
    private ModelProperties modelProperties;

    @Autowired
    private HttpClientUtil httpClientUtil;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public List<Detection> identify(String imageUrl) {
        String apiUrl = modelProperties.getApiUrl();
        String modelName = modelProperties.getName();

        if (apiUrl == null || apiUrl.isBlank()) {
            log.error("模型API URL未在配置文件中设置 (model.api-url)");
            return Collections.emptyList();
        }

        try {
            // 1. 构造请求
            Map<String, Object> requestBody = Map.of(
                    "image_url", imageUrl,
                    "model", modelName
            );

            // 2. 发送POST请求
            String jsonResponse = httpClientUtil.doPost(apiUrl, requestBody);
            log.info("从识别服务器收到响应: {}", jsonResponse);

            // 3. 解析响应
            if (jsonResponse == null || jsonResponse.isBlank()) {
                return Collections.emptyList();
            }

            List<ApiDetectionVo> apiDetections = objectMapper.readValue(jsonResponse, new TypeReference<>() {});

            // 4. 将响应映射到Detection实体
            List<Detection> detections = new ArrayList<>();
            for (ApiDetectionVo apiDetection : apiDetections) {
                List<Integer> p1 = apiDetection.getP1();
                List<Integer> p2 = apiDetection.getP2();

                if (p1 != null && p1.size() == 2 && p2 != null && p2.size() == 2) {
                    BoxVo box = new BoxVo(
                            p1.get(0),
                            p1.get(1),
                            p2.get(0) - p1.get(0),
                            p2.get(1) - p1.get(1)
                    );

                    Detection detection = Detection.builder()
                            .className(apiDetection.getCls())
                            .confidence(Float.parseFloat(apiDetection.getConf()))
                            .box(box)
                            .build();
                    detections.add(detection);
                }
            }
            return detections;

        } catch (Exception e) {
            log.error("调用害虫识别API时发生错误", e);
            return Collections.emptyList();
        }
    }
} 